//
//  ZMNetworkingManager.swift
//  ZMWeiboSwift
//
//  Created by pg on 2017/7/23.
//  Copyright © 2017年 pg. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
//网络请求类型
enum RequestType {
    case get
    case post
}


class ZMNetworkingManager: AFHTTPSessionManager {

    
    //提供全局访问点  单例
    static let sharedManager : ZMNetworkingManager = {
       
        let instance = ZMNetworkingManager(baseURL: URL(string: "http://iosapi.itcast.cn/loveBeen/"))
        
        //添加支持服务器端发送的数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/html")
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        //设置网络支持非安全类型的https
        //允许无效的https证书
        instance.securityPolicy.allowInvalidCertificates = true
        //不验证域名
        instance.securityPolicy.validatesDomainName = false
        
        
        //
        instance.requestSerializer = AFJSONRequestSerializer()
        
        return instance
    }()
    
    //封装get和post请求方法
    func request(type: RequestType ,urlStr: String,params: Any?,progressClosure:((Double)->())?,finsishCallBack:  (@escaping (Any?,Error?)->())){
        
        if type == .get{
            
            self.get(urlStr, parameters: params, progress: { (progres: Progress) in
                
                progressClosure?(progres.fractionCompleted)
                
            }, success: { (dataTask, response: Any?) in
                
                finsishCallBack(response,nil)
                
              }, failure: { (_ , error) in
                
                finsishCallBack(nil,error)
              })
            
        }else{
            
            self.post(urlStr, parameters: params, progress: { (pro : Progress) in
                
                print(pro.fractionCompleted)
                progressClosure?(pro.fractionCompleted)
                
                
            }, success: { (dataTask, response) in
                
                finsishCallBack(response,nil)
                
            }, failure: { (dataTask, error) in
                
                finsishCallBack(nil ,error)
            })
            
        }
        
        
        
    }
    
}
//分类相关数据请求
extension ZMNetworkingManager{
    
    func requestShopData(reloadDataCompaltion:@escaping((_ dataArray:[ZMCategoriesModel]? , _ isSuccess:Bool)->())){
        
        let url =  "supermarket.json.php"
        
        let paramas : [ String : Any] = [
            "call" : "5"
        ]
        
        SVProgressHUD.show(withStatus: "努力加载中...")
        request(type: .post, urlStr: url, params: paramas, progressClosure: { (downprogress:Double) in
           
            OperationQueue.init().addOperation({ 
                print(downprogress)
            })
            
            
        }) { (response, error) in
            if error != nil{
                reloadDataCompaltion(nil,false)
                return
            }
            
            
            let resultDic = response as! [String:Any]
            let dataDic = resultDic["data"] as! [String:Any]
            let categoryarr = dataDic["categories"]
            let productDic = dataDic["products"] as! [String: Any]
            
            let categoryModelArray : [ZMCategoriesModel] = NSArray.yy_modelArray(with: ZMCategoriesModel.self, json: categoryarr!) as! [ZMCategoriesModel]
            
            
            for categoryModel in categoryModelArray{
                
                // print("\(categoryModel.id)")
                if let cate_id = categoryModel.id
                {
                    //获取当前模型分类对应的产品
                    if  let category_proArr = productDic[cate_id]{
                        categoryModel.produceModels = NSArray.yy_modelArray(with: ZMProductsModel.self, json: category_proArr) as? [ZMProductsModel]
                    }
                }
            }
            
            SVProgressHUD.dismiss()
            
            reloadDataCompaltion(categoryModelArray,true)

        }
        
//       request(type: .post, urlStr: url, params: paramas, progress: nil) { (response, error) in
//        
//            if error != nil{
//            reloadDataCompaltion(nil,false)
//            return
//        }
//        
//        
//            let resultDic = response as! [String:Any]
//            let dataDic = resultDic["data"] as! [String:Any]
//            let categoryarr = dataDic["categories"]
//            let productDic = dataDic["products"] as! [String: Any]
//           
//            let categoryModelArray : [ZMCategoriesModel] = NSArray.yy_modelArray(with: ZMCategoriesModel.self, json: categoryarr!) as! [ZMCategoriesModel]
//        
//        
//            for categoryModel in categoryModelArray{
//                    
//                    // print("\(categoryModel.id)")
//                if let cate_id = categoryModel.id
//                {
//                    //获取当前模型分类对应的产品
//                    if  let category_proArr = productDic[cate_id]{
//                    categoryModel.produceModels = NSArray.yy_modelArray(with: ZMProductsModel.self, json: category_proArr) as? [ZMProductsModel]
//                    }
//                }
//           }
//        
//        
//            reloadDataCompaltion(categoryModelArray,true)
//        }
        
    }
 ////////
}

//搜索相关接口
extension ZMNetworkingManager{
    func requestSearchKeyWordsData(reloadDataCompaltion:@escaping((_ dataArray:[String]? , _ isSuccess:Bool)->())){
        
        let url =  "search.json.php"
        
        let paramas : [ String : Any] = [
            "call" : "6"
        ]
        request(type: .post, urlStr: url, params: paramas, progressClosure: nil) { (response, error) in
            
            if error != nil{
                reloadDataCompaltion(nil,false)
                return
            }
            let resultDic = response as! [String : Any]
            let dataDic = resultDic["data"] as! [String : Any]
            let keywordarr = dataDic["hotquery"] as! [String]
            
            reloadDataCompaltion(keywordarr,true)
           
           
        }
        
    }

    //搜索
    func requestSearchData(reloadDataCompaltion:@escaping((_ dataArray:[ZMProductsModel]? , _ isSuccess:Bool)->())){
        
        let url =  "promotion.json.php"
        
        let paramas : [ String : Any] = [
            "call" : "8"
        ]
        request(type: .post, urlStr: url, params: paramas, progressClosure: nil) { (response, error) in
            
            if error != nil{
                reloadDataCompaltion(nil,false)
                return
            }
            let resultDic = response as! [String : Any]
           
            let dataArray = resultDic["data"] as! [[String: Any]]
            
            let modelArray = NSArray.yy_modelArray(with: ZMProductsModel.self, json: dataArray) as! [ZMProductsModel]
            
            reloadDataCompaltion(modelArray,true)
            
            
        }
        
    }

}

